import Taro, { useEffect, useState, useMemo, useReachBottom } from '@tarojs/taro'
import {View, Text, Image, Picker, ScrollView} from '@tarojs/components'
import { AtTabs, AtTabsPane, AtAccordion, AtIcon } from 'taro-ui'
import m from 'moment'
import cloneDeep from 'lodash/cloneDeep'
import './index.scss'

// components
import CashList from "../../components/cashList";
import NoData from "../../components/noData";

// api
import api from '../../api/index';

// utils
import getLoginInfo from "../../utils/getLoginInfo";
import getAvatarImgPrefix from "../../utils/getAvatarImgPrefix";

// constance
import {CASH_OUT_STATUS} from '../../constances/constances'

export default function WithDrawRecord() {
  const [userBankTransferList, setUserBankTransferList] = useState([])
  const [userBankStatements, setUserBankStatements] = useState([])
  const [cashOutMap, setCashOutMap] = useState({})
  const [statementsMap, setStatementsMap] = useState({})
  const [current, setCurrent] = useState(0)
  const [cashOutPickerValue, setcashOutPickerValue] = useState('')
  const [loading, setLoading] = useState(false)
  const [isMore, setIsMore] = useState(false)
  const tabList = [{ title: '提现记录' }, { title: '账单明细' }]
  const PAGE_SIZE = 20

  useEffect( () => {
    const user = getLoginInfo()
    if(!user) {
      return
    }
    const avatar = getAvatarImgPrefix(user.user.avatar_url)
    const nickname = user.user.nickname
    getCashOutData(avatar, nickname)
    getStatementData()
  }, [])

  useReachBottom(() => {
    if (isMore) {
      console.log('1231231231231', userBankStatements)
      getStatementData(userBankStatements.length, (userBankStatements.length + PAGE_SIZE - 1))
    }
  })

  // ---- 提现记录逻辑
  async function getCashOutData(avatar, nickname) {
    const data = await api.user.getUserCashOut()
    if (data.code > 0) {
      const _userBankTransferList = JSON.parse(data.data).userBankTransferList
      if (_userBankTransferList.length > 0) {
        const map = {}
        const _listData = _userBankTransferList.map(item => {
          const apply_year_month = m(item.apply_date).format('YYYY年MM月')
          const _listItem = {
            avatar,
            name: nickname,
            num: '-' + item.transfer_cash_cent / 100,
            desc: `${m(item.apply_date).format('YYYY-MM-DD  HH:mm:ss')}  ${CASH_OUT_STATUS[item.operate_result]}`
          }
          if(map[apply_year_month]) {
            map[apply_year_month].push(_listItem)
          } else {
            map[apply_year_month] = [_listItem]
          }

          return {
            ...item,
            apply_year_month,
          }
        })

        setUserBankTransferList(_listData)
        setCashOutMap(map)
        // setCashOutMap({
        //   ...map,
        //   '2019年11月': map['2019年12月'].map(item => ({
        //     ...item,
        //     desc: item.desc.replace('12', '11')
        //   })),
        //   '2019年10月': map['2019年12月'].map(item => ({
        //     ...item,
        //     desc: item.desc.replace('12', '10')
        //   })),
        //   '2019年09月': map['2019年12月'].map(item => ({
        //     ...item,
        //     desc: item.desc.replace('12', '9')
        //   })),
        // })
      }
    }
  }

  function handleChangeCashPicker(e) {
    setcashOutPickerValue(`${e.detail.value.split('-').join('年')}月`)
  }

  const cashOutList = useMemo(() => {
    if (cashOutPickerValue) {
      return Object.keys(cashOutMap).filter(item => item == cashOutPickerValue)
    }

    return Object.keys(cashOutMap)
  }, [cashOutMap, cashOutPickerValue])

  //  提现记录逻辑 ----


  // ---- 账单清单逻辑
    async function getStatementData(start = 0, end = PAGE_SIZE - 1) {
      setLoading(true)
      const data = await api.user.getStatement({
        start,
        end
      })
      setLoading(false)
      if(data.code > 0) {
        const _userBankStatements = JSON.parse(data.data).userBankStatements
        if(_userBankStatements.length > 0) {
          const map = cloneDeep(statementsMap)
          const _listData = _userBankStatements.map(item => {
            const year_month = m(item.timeStamp).format('YYYY年MM月')
            const memoMap = {
              1: '返现',
              2: '提现',
            }
            const typeMap = {
              1: '+',
              2: ''
            }
            const _listItem = {
              title: item.memo ? item.memo : memoMap[item.type],
              desc: m(item.timeStamp).format('YYYY-MM-DD  HH:mm:ss'),
              money: item.moneyInCent / 100,
              icon: typeMap[item.type]
              // num: '-' + item.transfer_cash_cent / 100,
              // desc: `${m(item.apply_date).format('YYYY-MM-DD  HH:mm:ss')}  ${CASH_OUT_STATUS[item.operate_result]}`
            }
            if(map[year_month]) {
              map[year_month].push(_listItem)
            } else {
              map[year_month] = [_listItem]
            }

            return {
              ...item,
              year_month,
            }
          })

          if(_listData.length === PAGE_SIZE) {
            setIsMore(true)
          } else {
            setIsMore(false)
          }
          setUserBankStatements([
            ...userBankStatements,
            ..._listData,
          ])
          setStatementsMap(map)
        }

      }
    }

  const statementsList = useMemo(() => {
    return Object.keys(statementsMap)
  }, [statementsMap])

  // 账单清单逻辑 ----

  console.log(statementsMap, isMore)

  return (
    <View className='withdraw-record-page'>
      <View className='record-list-container'>
        <AtTabs current={current} tabList={tabList} onClick={value => setCurrent(value)}>
          <AtTabsPane current={current} index={0} >
            <View className='tabsPane'>
              {
                cashOutMap && cashOutList.length > 0 ? (
                  cashOutList.map((item, index) => (
                    <View className='record-list-wrapper' key={index}>
                      <Picker
                        mode='date'
                        fields='month'
                        value={item.replace('年', '-').replace('月', '')}
                        onChange={(e) => handleChangeCashPicker(e)}
                      >
                        <View className='title'>
                          <View className='date'>
                            <Text>{item}</Text>
                            <View className='arrow-container'>
                              <Text className='arrow' />
                            </View>

                          </View>
                          {/*<Text className='sum'>共提现￥499.9</Text>*/}
                        </View>
                      </Picker>
                      <CashList listData={cashOutMap[item]} />
                    </View>
                  ))
                ) : (
                  <View className='record-list-wrapper'>
                    {
                      cashOutPickerValue && (
                        <Picker
                          mode='date'
                          fields='month'
                          value={cashOutPickerValue.replace(
                            '年', '-').replace('月', '')}
                          onChange={(e) => handleChangeCashPicker(e)}
                        >
                          <View className='title'>
                            <View className='date'>
                              <Text>{cashOutPickerValue}</Text>
                              <View className='arrow-container'>
                                <Text className='arrow' />
                              </View>
                            </View>
                          </View>
                        </Picker>
                      )
                    }
                    <View className='no-data'>
                      <NoData />
                    </View>
                  </View>
                )
              }
            </View>
          </AtTabsPane>

          <AtTabsPane current={current} index={1} >
            {
              statementsMap && statementsList.length > 0 ? (
                <View>
                  {
                    statementsList.map((item, index) => (
                      <View className='record-list-wrapper' key={index}>
                        <View className='title'>
                          <View className='date'>
                            <Text>{item}</Text>
                            {/*<View className='arrow-container'>*/}
                            {/*  <Text className='arrow' />*/}
                            {/*</View>*/}
                          </View>
                        </View>
                        {
                          statementsMap[item].map((statement, i) => (
                            <View className='statement-container' key={i}>
                              <View className='detail-container'>
                                <View className='detail'>
                                  {
                                    statement.title
                                  }
                                </View>
                                <View className='time'>
                                  {
                                    statement.desc
                                  }
                                </View>
                              </View>

                              <View className='money-container'>
                                {
                                  statement.icon
                                }
                                {
                                  statement.money
                                }
                                <Image className='img' src={require('../../assets/coin24X24@2x.png')} />
                              </View>
                            </View>
                          ))
                        }
                      </View>
                    ))
                  }
                  {
                    loading && (
                      <View className='tips'>
                        加载中...
                      </View>
                    )
                  }

                  {
                    !isMore && (
                      <View className='tips'>
                        没有更多记录咯~
                      </View>
                    )
                  }
                </View>
              ) : (
                <View className='no-data'>
                  <NoData />
                </View>
              )
            }
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  )
}

WithDrawRecord.config = {
  navigationBarTitleText: '提现记录',
}
